package com.example.steam520.dao;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.steam520.entity.User;
import com.example.steam520.entity.Priv;
import com.example.steam520.entity.UserPriv;
import com.example.steam520.mapper.UserMapper;
import com.example.steam520.mapper.PrivMapper;
import com.example.steam520.mapper.UserPrivMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class UserDao {

    @Autowired
    private UserMapper userMapper; // 已修正字段名称

    @Autowired
    private PrivMapper privMapper;

    @Autowired
    private UserPrivMapper userPrivMapper;

    /** 根据用户名查询用户 */
    public User getUserByUsername(String username) {
        if (username == null || username.isEmpty()) {
            return null; // 防止无效参数造成异常
        }
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        return userMapper.selectOne(queryWrapper);
    }

    /** 根据用户ID查询权限列表 */
    public List<String> getUserPrivilegesByUserId(Integer userId) {
        if (userId == null) {
            return Collections.emptyList(); // 参数非法则提前返回
        }

        // 1. 查询用户拥有的所有权限ID
        LambdaQueryWrapper<UserPriv> userPrivWrapper = new LambdaQueryWrapper<>();
        userPrivWrapper.eq(UserPriv::getUserId, userId);
        List<UserPriv> userPrivList = userPrivMapper.selectList(userPrivWrapper);
        System.out.println(userPrivList);
        if (userPrivList.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 提取privId并一次性查出对应权限标识authority
        List<Integer> privIdList = userPrivList.stream()
                .map(UserPriv::getPrivId)
                .distinct() // 避免重复privId影响查询效率
                .collect(Collectors.toList());
        System.out.println(privIdList);
        LambdaQueryWrapper<Priv> privWrapper = new LambdaQueryWrapper<>();
        privWrapper.in(Priv::getId, privIdList);
        List<Priv> privList = privMapper.selectList(privWrapper);
        System.out.println(privList);
        // 3. 直接转换为authority列表返回
        return privList.stream()
                .map(Priv::getAuthority)
                .collect(Collectors.toList());
    }

}
